package com.ruoyi.feike.instener;

import com.github.pagehelper.util.StringUtil;
import com.ibm.icu.math.BigDecimal;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DayUtils;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.feike.domain.BasicInformation;
import com.ruoyi.feike.domain.DepositCalculation;
import com.ruoyi.feike.domain.HLimitSetupResult;
import com.ruoyi.feike.domain.LimitActiveProposal;
import com.ruoyi.feike.mapper.AnnualReviewyMapper;
import com.ruoyi.feike.mapper.BasicInformationMapper;
import com.ruoyi.feike.service.IDepositCalculationService;
import com.ruoyi.feike.service.IHLimitSetupResultService;
import com.ruoyi.feike.service.ILimitActiveProposalService;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;

@Slf4j
@Component
public class SetUpSendMailListener implements ExecutionListener , ApplicationContextAware {

    private Expression state;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    private static ApplicationContext context = null;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("开始发办结邮件");
        String activeProfile = context.getEnvironment().getActiveProfiles()[0];
        if(activeProfile.equals("dev")){
            isSendEmal = "true";
            url = "http://localhost:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }else if(activeProfile.equals("prod")){
            isSendEmal = "true";
            url = "http://10.226.185.146:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="";
        }else if (activeProfile.equals("uat")){
            isSendEmal = "true";
            url = "http://10.226.186.143:82";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }
        if(isSendEmal!=null && isSendEmal.equals("true")){
            String instanceId = delegateExecution.getProcessInstanceId();
            ArrayList<SysUser> users = new ArrayList<>();
            if(null !=instanceId) {
                Boolean isRefund = false;
                HistoryService historyService = SpringUtils.getBean(HistoryService.class);
                ILimitActiveProposalService limitActiveProposalService = SpringUtils.getBean(ILimitActiveProposalService.class);
                IDepositCalculationService depositCalculationService = SpringUtils.getBean(IDepositCalculationService.class);

                SysPostMapper sysPostMapper = SpringUtils.getBean(SysPostMapper.class);
                HistoricProcessInstance procInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
                String businessKey = procInstance.getBusinessKey();
                //
            /*    LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
                limitActiveProposal.setInstanceId(businessKey);
                List<LimitActiveProposal> limitActiveProposals = limitActiveProposalService.selectLimitActiveProposalList(limitActiveProposal);
                for (LimitActiveProposal who : limitActiveProposals) {
                    who.setSort(DayUtils.typeSort(who.getLimitType()));
                }
                limitActiveProposals.sort(Comparator.comparingInt(LimitActiveProposal::getSort));*/

                HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
                hLimitSetupResult.setInstanceid(businessKey);
                IHLimitSetupResultService limitSetupResultService = SpringUtils.getBean(IHLimitSetupResultService.class);
                List<HLimitSetupResult> hLimitSetupResults = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
                for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
                    limitSetupResult.setSort(DayUtils.typeSort(limitSetupResult.getLimittype()));
                }
                hLimitSetupResults.sort(Comparator.comparingInt(HLimitSetupResult::getSort));

                DepositCalculation depositCalculation1 = new DepositCalculation();
                depositCalculation1.setInstanceId(businessKey);
                List<DepositCalculation> depositCalculations = depositCalculationService.selectDepositCalculationList(depositCalculation1);
                for (DepositCalculation deposit : depositCalculations) {
                    deposit.setSort(DayUtils.typeSort(deposit.getLimitType()));
                    if(StringUtils.isNotEmpty(deposit.getProcess()) &&  deposit.getProcess().contains("Refund")){
                        //需要发送邮件
                        isRefund = true ;
                    }
                }
                depositCalculations.sort(Comparator.comparingInt(DepositCalculation::getSort));
              /*  SysUser sysUser = new SysUser();
                sysUser.setEmail("844132350@qq.com");
                sendMailByEmailInfo(sysUser,businessKey,depositCalculations,limitActiveProposals);*/
                ArrayList<String> groups = new ArrayList<>();
                ArrayList<String> userNames = new ArrayList<>();
                groups.add("underwriter");
                groups.add("supervisor");
                groups.add("credit manager");
                groups.add("dm");
                groups.add("op");
                for (String group : groups) {
                    System.out.println("groupId==" + group);
                    // 根据组查对应组成员id，在查到对应的用户对象信息
                    List<SysUser> userList = sysPostMapper.selectUserListByPostCode(group);
                    for (SysUser sysUser : userList) {
                        userNames.add(sysUser.getUserName());
                    }
                }
                if(userNames.size()>0){
                    ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
                    LinkedHashSet<String> hashSet = new LinkedHashSet<>(userNames);
                    ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
                    System.out.println("邮件接收人:"+listWithoutDuplicates);
                    for (String listWithoutDuplicate : listWithoutDuplicates) {
                        SysUser sysUser = userService.selectUserByUserName(listWithoutDuplicate);
                        log.info("邮件发送，收件人用户为{}",sysUser.getUserName());
                        try {
                            sendMailByEmailInfo(sysUser,businessKey,depositCalculations,hLimitSetupResults);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if(isRefund){
                        ArrayList<SysUser> sysUsers = new ArrayList<>();
                        SysUser sysUserPlm = new SysUser();
                        sysUserPlm.setEmail("Heather.Xu@stellantisafc.com.cn");
                        SysUser sysUserPlm1 = new SysUser();
                        sysUserPlm1.setEmail("ink.zhao@stellantisafc.com.cn");
                        SysUser sysUserPlm2 = new SysUser();
                        sysUserPlm2.setEmail("Ray.Lin@stellantisafc.com.cn");
                        SysUser sysUserPlm3 = new SysUser();
                        sysUserPlm3.setEmail("effie.xie@stellantisafc.com.cn");
                        SysUser sysUserPlm4 = new SysUser();
                        sysUserPlm4.setEmail("bruck.zhang@stellantisafc.com.cn");
                        sysUsers.add(sysUserPlm);
                        sysUsers.add(sysUserPlm1);
                        sysUsers.add(sysUserPlm2);
                        sysUsers.add(sysUserPlm3);
                        sysUsers.add(sysUserPlm4);
                        try {
                            for (SysUser sysUser : sysUsers) {
                                sendMailByEmailInfo(sysUser,businessKey,depositCalculations,hLimitSetupResults);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }

    public void sendMailByEmailInfo(SysUser user,String instanceId,List<DepositCalculation> depositCalculations,List<HLimitSetupResult> hLimitSetupResults) {
        try {
            StringBuilder contentStr = new StringBuilder();
            String dealer ="申请流程名称: WFS Limit Set-Up";
            String dealerName ="";
            String businessKey = "申请流程Coding:"+instanceId;
            String ln = "<br>";
            StringBuilder content = new StringBuilder("<html><head></head><body><h3>额度设置完毕</h3>");
            content.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size:16px;\">");
            content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>Sector</th><th>Limit Type</th><th>Active Limit</th><th>O/S</th><th>Limit Expiry Date</th></tr>");
            if(hLimitSetupResults!=null && hLimitSetupResults.size()>0){
                DecimalFormat df = new DecimalFormat("#,###");
                for (HLimitSetupResult limitActiveProposal : hLimitSetupResults) {
                    content.append("<tr>");
                    content.append("<td>" + limitActiveProposal.getSector() + "</td>"); //第一列
                    content.append("<td>" + limitActiveProposal.getLimittype() + "</td>"); //第二列
                    String amt ="";
                    String amt2 ="";
                    if(StringUtils.isNotEmpty(limitActiveProposal.getCurrentactivelimit())){
                        BigDecimal bigDecimal = new BigDecimal(limitActiveProposal.getCurrentactivelimit());
                        amt = NumberFormat.getNumberInstance().format(bigDecimal);
                    }
                    if(StringUtils.isNotEmpty(limitActiveProposal.getOs())){
                        BigDecimal bigDecimal2 = new BigDecimal(limitActiveProposal.getOs());
                        amt2 = NumberFormat.getNumberInstance().format(bigDecimal2);
                    }
                    content.append("<td>" + amt + "</td>"); //第三列
                    content.append("<td>" + amt2 + "</td>"); //第四列
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if(limitActiveProposal.getCurrentactivelimitexpirydate() != null ){
                        String format = sdf.format(limitActiveProposal.getCurrentactivelimitexpirydate());
                        content.append("<td>" + format + "</td>"); //第五列
                    }else{
                        content.append("<td>" + "" + "</td>"); //第五列
                    }
                    content.append("</tr>");
                    dealerName = limitActiveProposal.getDealername();
                }
            }

            content.append("</table>");
            content.append("</body></html>");
            StringBuilder content1 = new StringBuilder("<html><head></head><body><h3>保证金操作完毕</h3>");
            content1.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size:16px;\">");
            content1.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>Sector</th><th>Limit Type</th><th>Deposit Amount</th><th>Deposit GAP</th><th>Process</th><th>Transfer To</th><th>Transfer to limit Type</th><th>Transfer Amount</th></tr>");
            if(depositCalculations!=null && depositCalculations.size()>0){
                for (DepositCalculation deposit : depositCalculations) {
                    content1.append("<tr>");
                    content1.append("<td>" + deposit.getSector() + "</td>");
                    content1.append("<td>" + deposit.getLimitType() + "</td>");
                    if(StringUtils.isNotEmpty(deposit.getProposedAmount()) && StringUtils.isNotEmpty(deposit.getGap())){
                        String amt = deposit.getProposedAmount().replace(",", "");
                        BigDecimal bigDecimal = new BigDecimal(amt);
                        String amtStr = NumberFormat.getNumberInstance().format(bigDecimal);
                        content1.append("<td>" + amtStr + "</td>");
                    }else{
                        content1.append("<td>" + " " + "</td>");
                    }

                    if(StringUtils.isNotEmpty(deposit.getGap() ) && StringUtils.isNotEmpty(deposit.getGap())){
                        String amt = deposit.getGap().replace(",", "");
                        BigDecimal bigDecimal = new BigDecimal(amt);
                        String amtStr = NumberFormat.getNumberInstance().format(bigDecimal);
                        content1.append("<td>" + amtStr + "</td>");
                    }else{
                        content1.append("<td>" + " " + "</td>");
                    }
                    if(deposit.getProcess()!=null){
                        content1.append("<td>" + deposit.getProcess() + "</td>");
                    }else{
                        content1.append("<td>" + "" + "</td>");
                    }
                    if(deposit.getTransferTo()!=null){
                        content1.append("<td>" + deposit.getTransferTo() + "</td>");
                    }else{
                        content1.append("<td>" + "" + "</td>");
                    }
                    if(deposit.getTransfertolimittype()!=null){
                        content1.append("<td>" + deposit.getTransfertolimittype() + "</td>");
                    }else{
                        content1.append("<td>" + "" + "</td>");
                    }
                    if(deposit.getTransferAmount()!=null && StringUtils.isNotEmpty(deposit.getTransferAmount())){
                        String amt = deposit.getTransferAmount().replace(",", "");
                        BigDecimal bigDecimal = new BigDecimal(amt);
                        String amtStr = NumberFormat.getNumberInstance().format(bigDecimal);
                        content1.append("<td>" + amtStr + "</td>");
                    }else{
                        content1.append("<td>" + "" + "</td>");
                    }

                    content1.append("</tr>");
                    dealerName = deposit.getDealerName();
                }
            }
            content1.append("</table>");
            content1.append("</body></html>");
            contentStr.append(msg);
            contentStr.append(ln);
            contentStr.append(dealer);
            contentStr.append(ln);
            contentStr.append(dealerName);
            contentStr.append(ln);
            contentStr.append(businessKey);
            contentStr.append(ln);
            contentStr.append(content);
            contentStr.append(ln);
            contentStr.append(content1);

            // 测试文本邮件发送（无附件）
            String to = user.getEmail();
            if(!StringUtil.isEmpty(to)){
                System.out.println("发送任务到"+ to);
                String title = "WWS- WFS Limit Set-Up-"+dealerName+"-Completed";
                //带附件方式调用
                JavaMailSender bean = SpringUtils.getBean(JavaMailSender.class);
                new EmailUtil(from, bean).sendMessageCarryFiles(to, title, contentStr.toString(), null);
                // return AjaxResult.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
